package org.gen.code.db.controller;


import org.gen.code.core.response.R;
import org.gen.code.db.dao.DbConfigDao;
import org.gen.code.db.domain.DbConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据库控制层
 */
@RestController
@RequestMapping("/db/")
public class DBController {

    @Autowired
    private DbConfigDao dbConfigDao;


    /**
     * 获取数据库配置信息
     *
     * @param model
     * @return
     */
    @GetMapping("/getDbList")
    public R getDbList(Model model) {
        List<DbConfig> dbConfigList = dbConfigDao.findAll();
        return R.success(dbConfigList);
    }

    /**
     * 新增
     *
     * @param dbConfig
     * @return
     * @throws SQLException
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public R save(@RequestBody DbConfig dbConfig) throws SQLException {
        DbConfig save = dbConfigDao.save(dbConfig);
        return R.success("新增成功");
    }

    /**
     * 删除
     *
     * @param dbConfig
     * @return
     * @throws SQLException
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public R delete(@RequestBody DbConfig dbConfig) throws SQLException {
        dbConfigDao.delete(dbConfig);
        return R.success("删除成功");
    }

    /**
     * 测试数据库连接
     *
     * @param dbConfig
     * @return
     */
    @RequestMapping(value = "/test/connect", method = RequestMethod.POST)
    public R test(@RequestBody DbConfig dbConfig) throws SQLException {
        //创建用于连接数据库的Connection对象
        Connection con = null;
        try {
            // 加载Mysql数据驱动
            Class.forName(dbConfig.getDriver());
            // 创建数据连接
            con = DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUserName(), dbConfig.getPassword());
            if (con != null) {
                return R.success("连接成功");
            }
        } catch (Exception e) {
            System.out.println("数据库连接失败：" + e.getMessage());
            return R.failure("连接失败" + e.getMessage());
        }
        return R.failure("连接失败");
    }


}
